﻿namespace System.ServiceModel.DomainServices
{
    using System;
    using System.ComponentModel;
    using System.ComponentModel.DataAnnotations;
    using System.Runtime.Serialization;
    using System.ServiceModel.DomainServices.Server;

    internal class SerializationUtility
    {
        public static Type GetClientType(Type t)
        {
            if (System.ServiceModel.DomainServices.BinaryTypeUtility.IsTypeBinary(t))
            {
                return typeof(byte[]);
            }
            return t;
        }

        public static object GetClientValue(Type targetType, object value)
        {
            if (value == null)
            {
                return null;
            }
            if ((targetType == typeof(byte[])) && System.ServiceModel.DomainServices.BinaryTypeUtility.IsTypeBinary(value.GetType()))
            {
                return System.ServiceModel.DomainServices.BinaryTypeUtility.GetByteArrayFromBinary(value);
            }
            return value;
        }

        public static object GetServerValue(Type targetType, object value)
        {
            if (value == null)
            {
                return null;
            }
            byte[] bytes = value as byte[];
            if (System.ServiceModel.DomainServices.BinaryTypeUtility.IsTypeBinary(targetType) && (bytes != null))
            {
                return System.ServiceModel.DomainServices.BinaryTypeUtility.GetBinaryFromByteArray(bytes);
            }
            return value;
        }

        public static bool IsSerializableDataMember(PropertyDescriptor propertyDescriptor)
        {
            if (!System.ServiceModel.DomainServices.TypeUtility.IsPredefinedType(propertyDescriptor.PropertyType) && !System.ServiceModel.DomainServices.TypeUtility.IsSupportedComplexType(propertyDescriptor.PropertyType))
            {
                return false;
            }
            if (propertyDescriptor.Attributes[typeof(ExcludeAttribute)] != null)
            {
                return false;
            }
            if (propertyDescriptor.Attributes[typeof(AssociationAttribute)] != null)
            {
                return false;
            }
            if (propertyDescriptor.ComponentType.Attributes()[typeof(DataContractAttribute)] != null)
            {
                if (propertyDescriptor.Attributes[typeof(DataMemberAttribute)] == null)
                {
                    return false;
                }
            }
            else if (propertyDescriptor.Attributes[typeof(IgnoreDataMemberAttribute)] != null)
            {
                return false;
            }
            return true;
        }
    }
}

